<template>
  <div class="schedule-list">
    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" :icon="Plus" @click="handleCreate">
          新建日程
        </el-button>
      </div>
      
      <div class="toolbar-right">
        <!-- 视图切换 -->
        <el-radio-group v-model="viewMode" size="small" @change="handleViewChange">
          <el-radio-button label="month">月视图</el-radio-button>
          <el-radio-button label="list">列表视图</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 日历视图 -->
    <ScheduleCalendarView
      v-if="viewMode === 'month'"
      v-model:currentDate="currentDate"
      @date-click="handleCreate"
      @schedule-click="handleScheduleClick"
    />

    <!-- 列表视图 -->
    <ScheduleListView
      v-else
      v-model:searchKeyword="searchKeyword"
      v-model:filterStatus="filterStatus"
      v-model:filterPriority="filterPriority"
      v-model:currentPage="currentPage"
      v-model:pageSize="pageSize"
      @refresh="loadSchedules"
      @edit="handleEdit"
      @status-change="handleStatusChange"
      @delete="handleDelete"
    />

    <!-- 日程对话框 -->
    <ScheduleCreatOrModifyDialog
      v-model:visible="dialogVisible"
      :schedule="currentSchedule"
      :mode="dialogMode"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessageBox } from 'element-plus'
import {
  Plus
} from '@element-plus/icons-vue'
import { useScheduleStore } from '@/stores/schedule'
import type { ScheduleResponse } from '@/api/models'
import type { ScheduleStatus } from '@/api/models'
import ScheduleCreatOrModifyDialog from './ScheduleCreatOrModifyDialog.vue'
import ScheduleCalendarView from './ScheduleCalendarView.vue'
import ScheduleListView from './ScheduleListView.vue'

const scheduleStore = useScheduleStore()

// 状态
const searchKeyword = ref('')
const filterStatus = ref('pending')
const filterPriority = ref('medium')
const currentPage = ref(1)
const pageSize = ref(10)
const dialogVisible = ref(false)
const dialogMode = ref<'create' | 'edit'>('create')
const currentSchedule = ref<ScheduleResponse | null>(null)
const viewMode = ref<'month' | 'list'>('month')
const currentDate = ref(new Date())

// 计算属性

// 方法
const handleViewChange = () => {
  if (viewMode.value === 'month') {
    loadMonthSchedules()
  } else {
    // 切换到列表视图时，应用默认筛选条件
    filterStatus.value = 'pending'
    filterPriority.value = 'medium'
    loadSchedules()
  }
}



const handleScheduleClick = (schedule: ScheduleResponse) => {
  dialogMode.value = 'edit'
  currentSchedule.value = schedule
  dialogVisible.value = true
}

const handleEdit = (schedule: ScheduleResponse) => {
  dialogMode.value = 'edit'
  currentSchedule.value = schedule
  dialogVisible.value = true
}

const handleCreate = () => {
  dialogMode.value = 'create'
  currentSchedule.value = null
  dialogVisible.value = true
}

const loadMonthSchedules = async () => {
  try {
    const year = currentDate.value.getFullYear()
    const month = currentDate.value.getMonth()
    const startDate = new Date(year, month, 1)
    const endDate = new Date(year, month + 1, 0)
    
    await scheduleStore.fetchScheduleList({
      start_date: startDate.toISOString().split('T')[0],
      end_date: endDate.toISOString().split('T')[0]
    })
  } catch (error) {
    console.error('加载月度日程失败:', error)
  }
}

const loadSchedules = async () => {
  try {
    await scheduleStore.fetchScheduleList({
      keyword: searchKeyword.value,
      status: filterStatus.value,
      priority: filterPriority.value,
      page: currentPage.value,
      pageSize: pageSize.value
    })
  } catch (error) {
    console.error('加载日程列表失败:', error)
  }
}

const handleStatusChange = async (schedule: ScheduleResponse) => {
  const statusOptions: { value: ScheduleStatus; label: string }[] = [
    { value: 'pending', label: '待处理' },
    { value: 'in_progress', label: '进行中' },
    { value: 'completed', label: '已完成' },
    { value: 'cancelled', label: '已取消' }
  ]
  
  const currentStatusIndex = statusOptions.findIndex(opt => opt.value === schedule.status)
  const nextStatusIndex = (currentStatusIndex + 1) % statusOptions.length
  const nextStatus = statusOptions[nextStatusIndex]
  
  try {
    await scheduleStore.updateScheduleItemStatus(schedule.id, nextStatus.value)
  } catch (error) {
    console.error('更新状态失败:', error)
  }
}

const handleDelete = async (schedule: ScheduleResponse) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除日程"${schedule.title}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await scheduleStore.deleteExistingSchedule(schedule.id)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除日程失败:', error)
    }
  }
}

const handleDialogSuccess = () => {
  if (viewMode.value === 'month') {
    loadMonthSchedules()
  } else {
    loadSchedules()
  }
}

// 生命周期
onMounted(() => {
  if (viewMode.value === 'month') {
    loadMonthSchedules()
  } else {
    loadSchedules()
  }
})
</script>

<style scoped>
.schedule-list {
  padding: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: var(--card-bg);
  border-radius: var(--border-radius);
  box-shadow: 0 2px 12px var(--shadow-color);
}

.toolbar-left,
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}


/* 响应式设计 */
@media (max-width: 1200px) {
  .toolbar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .toolbar-left,
  .toolbar-right {
    justify-content: space-between;
    flex-wrap: wrap;
  }
}

@media (max-width: 768px) {
  .schedule-list {
    padding: 8px;
  }
  
  .toolbar {
    padding: 12px;
    gap: 12px;
  }
  
  .toolbar-left {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .toolbar-right {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
}

@media (max-width: 480px) {
  .schedule-list {
    padding: 4px;
  }
  
  .toolbar {
    padding: 8px;
    gap: 8px;
  }
  
  .toolbar-left {
    gap: 8px;
  }
  
  .toolbar-right {
    gap: 6px;
  }
  
  .toolbar-left .el-button,
  .toolbar-right .el-button {
    height: 36px;
    font-size: 12px;
    padding: 0 8px;
  }
  
  /* 视图切换按钮组 */
  :deep(.el-radio-group) {
    display: flex;
    width: 100%;
  }
  
  :deep(.el-radio-button) {
    flex: 1;
  }
  
  :deep(.el-radio-button__inner) {
    width: 100%;
    border-radius: 4px;
    font-size: 11px;
    padding: 8px 4px;
  }
}

/* 横屏模式优化 */
@media (max-width: 768px) and (orientation: landscape) {
  .toolbar {
    flex-direction: row;
    flex-wrap: wrap;
  }
  
  .toolbar-left {
    flex-direction: row;
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .toolbar-right {
    flex-direction: row;
    flex-wrap: wrap;
    gap: 8px;
  }
}
</style>
